Component({
  properties: {
    appointment: Object,
    disabled: Boolean,
    userView: Boolean,
  },
  data: {
    timeSider: [],
    courtHeader: [],
    appointmentBody: [],
    stateClass: ['state_disabled', 'state_occupied', 'state_locked', 'state_valid'],
    stateName: ['已禁用', '已预约', '已锁定', '可预约'],
    selectedState: [],
    selectedCoordinate: [],
    price: 0,
    offsetRid: 0, // 用户视角 rid 偏差
  },
  observers: {
    'appointment': function (appointment) {
      if (appointment !== null) this.initTable(appointment);
    }
  },
  methods: {
    initTable(appointment) {
      // 侧边栏
      const hh = Array.apply(null, { length: 25 }).map((o, i) => {
        let s = '00' + i;
        return s.substring(s.length - 2);
      });
      const mm = ['00', '30'];
      const timeSider = [];
      const start_time = appointment.stadium[0].start_time, end_time = appointment.stadium[0].end_time;
      for (let i = 0; i < 48; i++) {
        const timeStr = hh[i >> 1] + ':' + mm[i & 1];
        if (timeStr >= start_time && timeStr < end_time) timeSider.push(timeStr);
      }
      // 表头
      let courtHeader = appointment.courts;
      courtHeader.sort((a, b) => {
        if (a.sport_id != b.sport_id) return a.sport_id - b.sport_id;
        return a.court_name < b.court_name ? -1 : 1;
      });
      // 数据
      const appointmentBody = [], selectedState = [];
      const sku_state = appointment.sku_state, sku_remark = appointment.sku_remark;
      const userNowDay = (
        new Date((appointment._id.substring(appointment._id.indexOf('-') + 1)) * 1e5).Format('yyyy-MM-dd') === new Date().Format('yyyy-MM-dd') && this.data.userView
      );
      for (let i = 0, j = -1; i < 48; i++) {
        const timeStr = hh[i >> 1] + ':' + mm[i & 1];
        if (timeStr < start_time || timeStr >= end_time) continue;
        if (j == -1) this.setData({ offsetRid: i })
        ++j;
        // 用户视角不能看见超过当前时间的预约
        const unseen = userNowDay && timeStr <= (new Date().Format('hh:mm'));
        appointmentBody.push([]);
        selectedState.push([]);
        courtHeader.forEach(court => {
          selectedState[j].push(0);
          appointmentBody[j].push({
            // court_id: court._id,
            court_price: court.court_price,
            state: unseen ? 0 : sku_state[court._id][i],
            remark: sku_remark[court._id][i],
          })
        })
      }
      this.setData({ timeSider, courtHeader, appointmentBody, selectedState, selectedCoordinate: [], price: 0 })
    },
    onSelect(ev) {
      if (this.data.disabled) return;
      const data = ev.currentTarget.dataset;
      const rid = data.rid, cid = data.cid;
      // 如果可选
      if (this.data.appointmentBody[rid][cid].state === 3) {
        const selectedState = this.data.selectedState, selectedCoordinate = this.data.selectedCoordinate;
        // 锁场字段 court_id, idx
        if (selectedState[rid][cid] == 0) selectedCoordinate.push({ rid, cid });
        else selectedCoordinate.splice(selectedCoordinate.findIndex(o => o.rid == rid && o.cid == cid), 1);
        this.setData({
          selectedCoordinate,
          [`selectedState[${rid}][${cid}]`]: 1 - selectedState[rid][cid],
          price: this.data.price + (selectedState[rid][cid] ? -1 : 1) * this.data.appointmentBody[rid][cid].court_price
        });
        this.triggerEvent('select', { price: this.data.price })
      }
    },
    onCancelSelect(ev) {
      const idx = ev.currentTarget.dataset.idx, selectedCoordinate = this.data.selectedCoordinate;
      const rid = selectedCoordinate[idx].rid, cid = selectedCoordinate[idx].cid;
      selectedCoordinate.splice(idx, 1);
      this.setData({
        [`selectedState[${rid}][${cid}]`]: 0,
        selectedCoordinate,
        price: this.data.price - this.data.appointmentBody[rid][cid].court_price
      })
      this.triggerEvent('select', { price: this.data.price })
    }
  },
  behaviors: ['wx://component-export'],
  export() {
    const header = this.data.courtHeader, sider = this.data.timeSider;
    sider.push('24:00');
    const courtList = [], skuList = [];
    const offsetRid = this.data.offsetRid;
    this.data.selectedCoordinate.forEach(({ rid, cid }) => {
      const court = header[cid];
      courtList.push({
        court_name: court.court_name,
        court_price: court.court_price,
        time_quantum: [sider[rid], sider[rid + 1]]
      })
      skuList.push({
        court_id: court._id,
        rid: rid + offsetRid
      })
    })
    return { courtList, skuList }
  }
})
